<template>
  <div v-loading="loading">
    <!-- 统计部分 -->
    <div class="statistics-container mb-20px">
      <el-row :gutter="20" justify="space-between">
        <el-col :span="4">
          <div class="statistic-card">
            <el-progress
              type="circle"
              :percentage="100"
              :width="120"
              :stroke-width="8"
              color="#F56C6C"
            >
              <div class="progress-content">
                <div class="progress-title">过敏食物</div>
                <div class="progress-number"
                  >{{ allergyData.allergyFoodCount || 0 }}<span class="progress-unit">种</span></div
                >
              </div>
            </el-progress>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="statistic-card">
            <el-progress
              type="circle"
              :percentage="100"
              :width="120"
              :stroke-width="8"
              color="#409EFF"
            >
              <div class="progress-content">
                <div class="progress-title">包含班级</div>
                <div class="progress-number"
                  >{{ allergyData.allergyClassCount || 0
                  }}<span class="progress-unit">个</span></div
                >
              </div>
            </el-progress>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="statistic-card">
            <el-progress
              type="circle"
              :percentage="100"
              :width="120"
              :stroke-width="8"
              color="#E6A23C"
            >
              <div class="progress-content">
                <div class="progress-title">总人数</div>
                <div class="progress-number"
                  >{{ allergyData.studentCount || 0 }}<span class="progress-unit">人</span></div
                >
              </div>
            </el-progress>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="statistic-card">
            <el-progress
              type="circle"
              :percentage="100"
              :width="120"
              :stroke-width="8"
              color="#8595F4"
            >
              <div class="progress-content">
                <div class="progress-title">男生</div>
                <div class="progress-number"
                  >{{ allergyData.boyCount || 0 }}<span class="progress-unit">人</span></div
                >
              </div>
            </el-progress>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="statistic-card">
            <el-progress
              type="circle"
              :percentage="100"
              :width="120"
              :stroke-width="8"
              color="#FB7299"
            >
              <div class="progress-content">
                <div class="progress-title">女生</div>
                <div class="progress-number"
                  >{{ allergyData.girlCount || 0 }}<span class="progress-unit">人</span></div
                >
              </div>
            </el-progress>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 筛选器 -->
    <div class="filter-container mb-15px">
      <el-radio-group v-model="displayMode" @change="handleDisplayModeChange">
        <el-radio-button label="food">按食物列表显示</el-radio-button>
        <el-radio-button label="class">按班级列表显示</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 表格部分 -->
    <div class="table-container">
      <!-- 按食物列表显示 -->
      <el-table
        v-if="displayMode === 'food'"
        :data="foodGroupedData"
        border
        style="width: 100%"
        row-key="foodId"
      >
        <el-table-column prop="foodName" label="食物名称" width="150" />
        <el-table-column prop="recipeNames" label="涉及食谱">
          <template #default="{ row }">
            <el-tag v-for="recipe in row.recipeNames" :key="recipe" class="mr-5px" type="success">
              {{ recipe }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="allergyCount" label="过敏人数（人）" width="130" />
        <el-table-column prop="classes" label="涉及班级">
          <template #default="{ row }">
            <el-tag v-for="className in row.classes" :key="className" class="mr-5px" type="info">
              {{ className }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="students" label="涉及学生">
          <template #default="{ row }">
            <el-tag v-for="student in row.students" :key="student" class="mr-5px">
              {{ student }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 按班级列表显示 -->
      <el-table v-else :data="classGroupedData" border style="width: 100%" row-key="classId">
        <el-table-column prop="className" label="班级名称" width="150" />
        <el-table-column prop="recipeNames" label="涉及食谱">
          <template #default="{ row }">
            <el-tag v-for="recipe in row.recipeNames" :key="recipe" class="mr-5px" type="success">
              {{ recipe }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="allergyCount" label="过敏人数" width="100" />
        <el-table-column prop="foods" label="过敏食物">
          <template #default="{ row }">
            <el-tag v-for="food in row.foods" :key="food" class="mr-5px" type="warning">
              {{ food }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="students" label="涉及学生">
          <template #default="{ row }">
            <el-tag v-for="student in row.students" :key="student" class="mr-5px">
              {{ student }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { RecipeMenusDailyApi } from '@/api/school/recipe/menusDaily'
import { getDictLabel, DICT_TYPE } from '@/utils/dict'
// 定义组件名称
defineOptions({
  name: 'AllergyTable'
})

// 定义组件属性
const props = defineProps({
  currentWeeklyMenu: {
    type: Object,
    default: () => ({})
  },
  loading: {
    type: Boolean,
    default: false
  }
})

// 定义事件
const emit = defineEmits(['update:loading'])

// 数据相关
const allergyData = ref({
  allergyFoodCount: 0,
  allergyClassCount: 0,
  studentCount: 0,
  boyCount: 0,
  girlCount: 0,
  foodAllergyList: []
})

// 显示模式：food-按食物显示，class-按班级显示
const displayMode = ref('food')

// 加载过敏统计数据
const loadAllergyData = async (menuId: number) => {
  if (!menuId) return

  emit('update:loading', true)
  try {
    const res = await RecipeMenusDailyApi.getRecipeFoodAllergyReport(menuId)
    allergyData.value = res
  } catch (err) {
    console.error('加载过敏统计数据失败', err)
  } finally {
    emit('update:loading', false)
  }
}

// 通用数据格式化函数
const formatGroupedData = (data: any[], keyField: string, groupFields: string[]) => {
  if (!data || data.length === 0) {
    return []
  }

  const grouped = new Map()
  data.forEach((item) => {
    if (!grouped.has(item[keyField])) {
      // 初始化分组对象
      const groupObj: any = {
        [keyField]: item[keyField],
        allergyCount: 0
      }

      // 为每个分组字段创建Set
      groupFields.forEach((field) => {
        groupObj[field] = new Set()
      })

      grouped.set(item[keyField], groupObj)
    }

    // 添加各项数据到对应的Set中
    const group = grouped.get(item[keyField])
    groupFields.forEach((field) => {
      // 特殊处理字段名映射
      let sourceField = field
      if (field === 'classes') sourceField = 'className'
      if (field === 'students') sourceField = 'studentName'
      if (field === 'foods') sourceField = 'foodName'
      if (field === 'recipeNames') sourceField = 'recipeName'
      let value = item[sourceField]
      if (sourceField === 'className' && item.schoolCode) {
        value = `${getDictLabel(DICT_TYPE.SCHOOL_CODE, item.schoolCode)}-${value}`
      }
      group[field].add(value)
    })

    // 更新过敏人数
    group.allergyCount = group.students?.size || 0
  })

  // 转换Set为Array
  return Array.from(grouped.values()).map((item) => {
    const result: any = { ...item }
    groupFields.forEach((field) => {
      result[field] = Array.from(item[field])
    })
    return result
  })
}

// 按食物分组的数据
const foodGroupedData = computed(() => {
  return formatGroupedData(allergyData.value.foodAllergyList, 'foodId', [
    'foodName',
    'recipeNames',
    'classes',
    'students'
  ])
})

// 按班级分组的数据
const classGroupedData = computed(() => {
  return formatGroupedData(allergyData.value.foodAllergyList, 'classId', [
    'className',
    'recipeNames',
    'foods',
    'students'
  ])
})

// 处理显示模式切换
const handleDisplayModeChange = () => {
  // 切换显示模式时不需要额外处理，computed会自动更新
}

// 监听currentWeeklyMenu变化
watch(
  () => props.currentWeeklyMenu,
  (newVal) => {
    if (newVal && newVal.menuId) {
      loadAllergyData(newVal.menuId)
    }
  },
  { immediate: true }
)

// 暴露方法给父组件
defineExpose({
  loadAllergyData
})
</script>

<style lang="scss" scoped>
.statistics-container {
  padding: 20px;
  border-radius: 4px;
}

.statistic-card {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 150px;
  background-color: white;
  border-radius: 8px;
}

.progress-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.progress-title {
  margin-bottom: 5px;
  font-size: 14px;
  color: #606266;
}

.progress-number {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
}

.progress-unit {
  margin-left: 2px;
  font-size: 12px;
}

.filter-container {
  display: flex;
  justify-content: flex-start;
}
</style>
